package cn.myframe;

import cn.myframe.config.ZkClient;
import cn.myframe.properties.ZookeeperProperties;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.TreeCacheEvent;
import org.apache.curator.framework.recipes.cache.TreeCacheListener;
import org.apache.zookeeper.CreateMode;
import org.junit.Test;

import java.io.UnsupportedEncodingException;

/*******************
 *@Describe
 *@author 封神梦
 *@Time 2022/4/19
 *@Company http://com.yiview.com
 ****************/
public class ZookeeperTest {

    @Test
    public  void zkCliTest(){
        ZookeeperProperties  properties = new ZookeeperProperties();
        properties.setServer("127.0.0.1:2181");
        properties.setNamespace("fsm");
        ZkClient client = new ZkClient(properties);
        client.init();
        client.createNode(CreateMode.PERSISTENT,"/yiview","fsm test data ");
    }

    @Test
    public  void zkCliReadTest(){
        ZookeeperProperties  properties = new ZookeeperProperties();
        properties.setServer("127.0.0.1:2181");
        properties.setNamespace("brokers");
        ZkClient client = new ZkClient(properties);
        client.init();
        byte[] nodeData = client.getNodeData("/ids/0");
        try {
            System.out.println("节点内容："+new String(nodeData,"gbk"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    @Test
    public  void zkCliWatchTest(){
        ZookeeperProperties  properties = new ZookeeperProperties();
        properties.setServer("127.0.0.1:2181");
        properties.setNamespace("fsm");
        ZkClient client = new ZkClient(properties);
        client.init();

        client.watchPath("/yiview", new TreeCacheListener() {
            @Override
            public void childEvent(CuratorFramework curatorFramework, TreeCacheEvent treeCacheEvent) throws Exception {
                byte[] nodeData = client.getNodeData("/yiview");
                System.out.println("节点内容："+new String(nodeData, "gbk"));
            }
        });
        try {
            Thread.sleep(500000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
